using System;
using Tycho.Parser.Peg;

namespace Tycho.Grammar {
    public class AnonymousNonTerminalCompiler : IProductionCompiler {
        private readonly IRuleCompiler RuleCompiler;
        private readonly Func<ICaptureCounter> CreateCaptureCounter;

        public AnonymousNonTerminalCompiler (IRuleCompiler ruleCompiler) : this (ruleCompiler, () => new CaptureCounter ()) {}

        public AnonymousNonTerminalCompiler (IRuleCompiler ruleCompiler, Func<ICaptureCounter> createCaptureCounter) {
            RuleCompiler = ruleCompiler;
            CreateCaptureCounter = createCaptureCounter;
        }

        public GrammarTree Compile (ITerm term, ChoicePrecedence precedence, ProductionCompilerContext context) {
            ITerm ruleTerm = ((CompositeTerm) term).SubTerms["rule"];
            IRule rule = RuleCompiler.Compile (ruleTerm, context, CreateCaptureCounter ());

            return new GrammarTree (new RuleProduction (rule));
        }
    }
}